<?php
class Xtutuquan{
    /**
     * 友好显示var_dump
     */
    static public function dump( $var, $echo = true, $label = null, $strict = true ) {
        $label = ( $label === null ) ? '' : rtrim( $label ) . ' ';
        if ( ! $strict ) {
            if ( ini_get( 'html_errors' ) ) {
                $output = print_r( $var, true );
                $output = "<pre>" . $label . htmlspecialchars( $output, ENT_QUOTES ) . "</pre>";
            } else {
                $output = $label . print_r( $var, true );
            }
        } else {
            ob_start();
            var_dump( $var );
            $output = ob_get_clean();
            if ( ! extension_loaded( 'xdebug' ) ) {
                $output = preg_replace( "/\]\=\>\n(\s+)/m", "] => ", $output );
                $output = '<pre>' . $label . htmlspecialchars( $output, ENT_QUOTES ) . '</pre>';
            }
        }
        if ( $echo ) {
            echo $output;
            return null;
        } else
            return $output;
    }
    /**
     * 获取和设置配置参数 支持批量定义
     * @param string|array $name 配置变量
     * @param mixed $value 配置值
     * @param mixed $default 默认值
     * @return mixed
     */
    static public function C($name=null, $value=null,$default=null) {
        static $_config = array();
        // 无参数时获取所有
        if (empty($name)) {
            return $_config;
        }
        // 优先执行设置获取或赋值
        if (is_string($name)) {
            if (!strpos($name, '.')) {
                $name = strtoupper($name);
                if (is_null($value))
                    return isset($_config[$name]) ? $_config[$name] : $default;
                $_config[$name] = $value;
                return;
            }
            // 二维数组设置和获取支持
            $name = explode('.', $name);
            $name[0]   =  strtoupper($name[0]);
            if (is_null($value))
                return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
            $_config[$name[0]][$name[1]] = $value;
            return;
        }
        // 批量设置
        if (is_array($name)){
            $_config = array_merge($_config, array_change_key_case($name,CASE_UPPER));
            return;
        }
        return null; // 避免非法参数
    }
    static public function session($name='',$value='') {
    $prefix   =  'tutuquan';
    if(is_array($name)) { // session初始化 在session_start 之前调用
        if(isset($name['prefix'])) self::C('SESSION_PREFIX',$name['prefix']);
        if(self::C('VAR_SESSION_ID') && isset($_REQUEST[self::C('VAR_SESSION_ID')])){
            session_id($_REQUEST[self::C('VAR_SESSION_ID')]);
        }elseif(isset($name['id'])) {
            session_id($name['id']);
        }
        if('common' != APP_MODE){ // 其它模式可能不支持
            ini_set('session.auto_start', 0);
        }
        if(isset($name['name']))            session_name($name['name']);
        if(isset($name['path']))            session_save_path($name['path']);
        if(isset($name['domain']))          ini_set('session.cookie_domain', $name['domain']);
        if(isset($name['expire']))          ini_set('session.gc_maxlifetime', $name['expire']);
        if(isset($name['use_trans_sid']))   ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
        if(isset($name['use_cookies']))     ini_set('session.use_cookies', $name['use_cookies']?1:0);
        if(isset($name['cache_limiter']))   session_cache_limiter($name['cache_limiter']);
        if(isset($name['cache_expire']))    session_cache_expire($name['cache_expire']);
        if(isset($name['type']))            self::C('SESSION_TYPE',$name['type']);
        if(self::C('SESSION_TYPE')) { // 读取session驱动
            $type   =   self::C('SESSION_TYPE');
            $class  =   strpos($type,'\\')? $type : 'Think\\Session\\Driver\\'. ucwords(strtolower($type));
            $hander =   new $class();
            session_set_save_handler(
                array(&$hander,"open"),
                array(&$hander,"close"),
                array(&$hander,"read"),
                array(&$hander,"write"),
                array(&$hander,"destroy"),
                array(&$hander,"gc"));
        }
        // 启动session
        if(C('SESSION_AUTO_START'))  session_start();
    }elseif('' === $value){
        if(''===$name){
            // 获取全部的session
            return $prefix ? $_SESSION[$prefix] : $_SESSION;
        }elseif(0===strpos($name,'[')) { // session 操作
            if('[pause]'==$name){ // 暂停session
                session_write_close();
            }elseif('[start]'==$name){ // 启动session
                session_start();
            }elseif('[destroy]'==$name){ // 销毁session
                $_SESSION =  array();
                session_unset();
                session_destroy();
            }elseif('[regenerate]'==$name){ // 重新生成id
                session_regenerate_id();
            }
        }elseif(0===strpos($name,'?')){ // 检查session
            $name   =  substr($name,1);
            if(strpos($name,'.')){ // 支持数组
                list($name1,$name2) =   explode('.',$name);
                return $prefix?isset($_SESSION[$prefix][$name1][$name2]):isset($_SESSION[$name1][$name2]);
            }else{
                return $prefix?isset($_SESSION[$prefix][$name]):isset($_SESSION[$name]);
            }
        }elseif(is_null($name)){ // 清空session
            if($prefix) {
                unset($_SESSION[$prefix]);
            }else{
                $_SESSION = array();
            }
        }elseif($prefix){ // 获取session
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$prefix][$name1][$name2])?$_SESSION[$prefix][$name1][$name2]:null;
            }else{

                return isset($_SESSION[$prefix][$name]) ? $_SESSION[$prefix][$name] : null;
            }
        }else{
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$name1][$name2])?$_SESSION[$name1][$name2]:null;
            }else{
                return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
            }
        }
    }elseif(is_null($value)){ // 删除session
        if($prefix){
            unset($_SESSION[$prefix][$name]);
        }else{
            unset($_SESSION[$name]);
        }
    }else{ // 设置session
        if($prefix){
            if (!isset($_SESSION[$prefix])) {
                $_SESSION[$prefix] = array();
            }
            $_SESSION[$prefix][$name]   =  $value;
        }else{
            $_SESSION[$name]  =  $value;
        }
    }
    }


    /**
     * @author Asa_yang <88683231@qq.com>
     * @link http://www.hoohg.com/
     * @copyright Copyright &copy; 2011-2013 Hoohg Software LLC
     * @param string $length 随机hash的长度
     * @return hash 返回生成的哈希字符串
     *
     */
    //随机hash生成
    static public function randStr($length=10){
        $hash='';
        $chars= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   //@#!~?:-
        $max=strlen($chars)-1;
//        mt_srand((double)microtime()*1000000);
        for($i=0;$i<$length;$i++){
            $hash .=$chars[mt_rand(0,$max)];
        }
        return $hash;
    }

    /**
     * @return string 创建唯一订单号
     */
    static public function createOrder(){
        $hash='';
        $chars= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $max=strlen($chars)-1;
        for($i=0;$i<3;$i++){
            $hash .=$chars[mt_rand(0,$max)];
        }
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        /* PHPALLY + 年月日 + 6位随机数  5O5-20150411-28301059 4+8+1+8 */
        return $hash .'-'. date('Ymd') .'-'. str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT);
    }
    /**
     * 获取客户端IP地址
     */
    static public function getClientIP() {
        static $ip = NULL;
        if ( $ip !== NULL )
            return $ip;
        if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
            $arr = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
            $pos = array_search( 'unknown', $arr );
            if ( false !== $pos )
                unset( $arr[$pos] );
            $ip = trim( $arr[0] );
        } elseif ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $ip = ( false !== ip2long( $ip ) ) ? $ip : '0.0.0.0';
        return $ip;
    }
    /**
     * 跳转页面 在基类中.
     * @author Asa_yang <88683231@qq.com>
     * @link http://www.hoohg.com/
     * @copyright Copyright &copy; 2011-2013 Hoohg Software LLC
     * @param string $message 弹窗提示文字 .
     * @param string $status 状态,为  success.
     * @param integer $time 跳转时间
     * @param string $url  跳转地址
     * @return html 返回弹窗界面
     */
    static public function redirect_message($message='操作成功',$status='success',$time=3,$url=false){

        $back_color ='#ff0000';
        if($status =='success'){
            $back_color= 'blue';
        }elseif($status == 'error'){
            $back_color= 'red';
        }
        if(is_array($url)){
            $route=isset($url[0]) ? $url[0] : '';
            $url=$this->createUrl($route,array_splice($url,1));
        }
        if ($url)
        {
            $url = "window.location.href='{$url}'";
        }
        else
        {
            $url = "history.back();";
        }
        $imagepath  = Yii::app()->baseUrl.'/static/admin/images/loading.gif';

        echo <<<HTML
			<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			<html>
			<head>
			<title>页面提示</title>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
			<style type="text/css" rel="stylesheet">
			body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, textarea, p, blockquote, th, td, img, input, select {margin:0; padding:0;}
			dl, dt, dd, ul, ol, li{list-style:none; list-style-position:outside;}
			li, img {vertical-align:bottom;}
			.clear {font-size:0; line-height:0; height:0; clear:both; overflow:hidden;}
			.clearfix:after {clear: both;content: ".";display: block; height: 0;visibility: hidden;}
			* html .clearfix             { zoom: 1; } /* IE6 */
			*:first-child+html .clearfix { zoom: 1; } /* IE7 */
			/*全局*/
			body {background:#F4F4F4}
			.main {width:500px; position:absolute;left:50%; top:20%; margin:0 0 0 -250px; background:#FFFFFF; border:1px solid #DEDEDE; border-radius:5px; box-shadow:0 1px 3px #CCCCCC; padding:20px}
			h1 {font:normal 25px/50px "microsoft yahei"; color:#0085CC; margin:0 0 10px 0}
			#blue {color:#0085CC;}
			#red {color:-moz-activehyperlinktext};
			p {font:normal 14px/23px "microsoft yahei"; color:#797979}
			p a {margin:0 2px; color:#0055CC}
			</style>
			</head>
			<body >
				<div class="main">
				<h1 id="{$back_color}">{$message}</h1><br/><p>页面将在<span id="sec" style="color:{$back_color};">{$time}</span>秒内自动跳转，如果不想等待，请点击 <a href="javascript:history.back(-1);">这里</a>跳转。</p>
				<script type="text/javascript">
					var timer;
                    function run(){
                        var s = document.getElementById("sec");
                        if(s.innerHTML == 0){
                        	clearInterval(timer);
                        	{$url}
                            return false;
                        }
                        s.innerHTML = s.innerHTML * 1 - 1;

                    }
                    timer = window.setInterval("run();", 1000);
                </script>
			</div>
			</body>
			</html>
HTML;
        exit;

    }

    /*
     * cookie加密
     * 加密 不带第二个参数   解密第二个参数为1
     */

    static public function encryption($username,$type = 0){
        $key = md5(sha1(Yii::app()->params['cookieKey']));
        if(!$type){
            return base64_encode($username ^ $key);
        }
        $username = base64_decode($username);
        return $username ^ $key;
    }


    /**
     * 2014 2 17
     */
    /**
     * 设置cookie
     * 第三个参数必填   为time()+xxx秒
     */
    static public function _cookiesSet ($name = '', $value = '', $expire = 3600, $path = '', $domain = '', $secure = false)
    {

        $cookieSet = new CHttpCookie($name, $value);
        $expire && $cookieSet->expire = $expire;
        $path && $cookieSet->path = $path;
        $domain && $cookieSet->domain = $domain;
        $secure && $cookieSet->secure = $secure;
        Yii::app()->request->cookies[$name] = $cookieSet;
    }

    /**
     * 获取cookie
     */
    static public function _cookiesGet ($name, $once = false)
    {
        $cookie = Yii::app()->request->getCookies();
        if($cookie[$name]){
            $data = $cookie[$name]->value;
        }else{
            $data = '';
        }

        if ($once)
            unset($cookie[$name]);
        return $data;
    }

    /**
     * 清理cookie
     * @param  $name
     */
    static public  function _cookiesRemove ($name)
    {
        $cookie = Yii::app()->request->getCookies();
        unset($cookie[$name]);
    }

    static public function getEmailConfig(){
        //email 配置
        $value = Yii::app()->cache->get('system_email');
        if($value === false){
            // 因为在缓存中没找到，重新生成 $value
            $email_info = Config::model()->findAll('type=:type',array(':type'=>'email'));
            $data = array();
            foreach($email_info as $v){
                $data[$v->name] = $v->value;
            }
            Yii::app()->cache->set('system_email',$data);
            $value = $data;
        }
        return $value;
    }

    static public function _sendEmail($to,$Subject,$content){
        $value = self::getEmailConfig();
        $mailer = Yii::createComponent('ext.mailer.EMailer');
        $mailer->Host = $value['emailHost'];
        $mailer->IsSMTP();
        $mailer->SMTPAuth = true;
        $mailer->From = $value['emailFrom'];
        $mailer->AddReplyTo($value['emailFrom']);
        $mailer->AddAddress($to);
        $mailer->FromName = $value['emailFromName'];
        $mailer->Username = $value['emailFrom'];    //这里输入发件地址的用户名
        $mailer->Password = $value['emailPassword'];   //这里输入发件地址的密码
        $mailer->SMTPDebug = FALSE;   //设置SMTPDebug为true，就可以打开Debug功能，根据提示去修改配置
        $mailer->CharSet = 'UTF-8';
        $mailer->Subject = $Subject;
        $mailer->Body = $content;
        $status = $mailer->Send();
        return $status;
    }
    /**
     * 反引用一个引用字符串
     * @param  $string
     * @return string
     */
    static function stripslashes($string) {
        if(is_array($string)) {
            foreach($string as $key => $val) {
                $string[$key] = self::stripslashes($val);
            }
        } else {
            $string = stripslashes($string);
        }
        return $string;
    }
    /**
     * 返回经stripslashes处理过的字符串或数组
     * @param $string 需要处理的字符串或数组
     * @return mixed
     */
    static public function new_stripslashes($string) {
        if (!is_array($string)) return stripslashes($string);
        foreach($string as $key => $val) $string[$key] = self::new_stripslashes($val);
        return $string;
    }
    /**
     * 验证邮箱
     */
    public static function email( $str ) {
        if ( empty( $str ) )
            return true;
        $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
        if ( strpos( $str, '@' ) !== false && strpos( $str, '.' ) !== false ) {
            if ( preg_match( $chars, $str ) ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 循环创建目录
     */
    static public function mkdir( $dir, $mode = 0777 ) {
        if ( is_dir( $dir ) || @mkdir( $dir, $mode))
            return true;
        if ( !self::mkdir(dirname($dir), $mode))
            return false;
        return @mkdir( $dir, $mode );
    }
    /**
     * 将字符串转换为数组
     *
     * @param	string	$data	字符串
     * @return	array	返回数组格式，如果，data为空，则返回空数组
     */
    static function string2array($data) {
        if($data == '') return array();
        @eval("\$array = $data;");
        return @$array;
    }
    /**
     * 将数组转换为字符串
     *
     * @param	array	$data		数组
     * @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
     * @return	string	返回字符串，如果，data为空，则返回空
     */
    static function array2string($data, $isformdata = 1) {
        if($data == '') return '';
        if($isformdata) $data = self::new_stripslashes($data);
        return addslashes(var_export($data, TRUE));
    }


    /*
      *功能：下载远程图片保存到本地
      *参数：远程图片url,
      *     文件夹路径，
      *     文件路径
      *当保存文件名称为空时则使用远程文件原来的名称
      */
    static public function getImage($url,$savefile,$filename){
        if($url==''){return false;}
        if(!is_dir($savefile)) mkdir($savefile, 0777,true);
        if(!is_readable($savefile)) chmod($savefile, 0777);
        $hander = curl_init();
        $fp = fopen($filename,'wb');
        curl_setopt($hander,CURLOPT_URL,$url);
        curl_setopt($hander,CURLOPT_FILE,$fp);
        curl_setopt($hander,CURLOPT_HEADER,0);
        curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($hander,CURLOPT_TIMEOUT,60);
        $output = curl_exec($hander);
        curl_close($hander);
        fclose($fp);
        require_once('Tp/ThinkImage/Image.class.php');
        $image = new Image();
        $thumbPath = $savefile.'/200x200.jpg';
        $unfoldPath = $savefile.'/36x36.jpg';
        $image->open($filename);
        $image->thumb(200, 200)->save($thumbPath);
        $image->open($filename);
        $image->thumb(36, 36)->save($unfoldPath);
        return $output;
    }
    /**
     * 获取邮件
     */
    static public function getUserEmail($id,$group_id){
            $count = Message::model()->getUserMessage($id,$group_id);
        return $count;
    }
    static public function getUserEvent($uid){
        $count = Event::model()->getCountEvent($uid);
        return $count;
    }



    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @return void
     */
    static public function ajaxReturn($data,$type='') {
        if(empty($type)) $type  =   'JSON';
        switch (strtoupper($type)){
            case 'JSON' :
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data));
            case 'XML'  :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler  =   isset($_GET['callback']) ? $_GET['callback'] : 'jsonpReturn';
                exit($handler.'('.json_encode($data).');');
            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
        }
    }

    static public function getAvatar($id,$size = 100){
        $dir1 = ceil($id / 10000);
        $dir2 = ceil($id % 10000 / 1000);
        $upload = Yii::app()->params['uploadPath'];
        $dir = Yii::app()->params['imgPath'].$upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/';
        if($size == 100){
            $url = $dir.'100x100.jpg';
            $curl = $upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/'.'100x100.jpg';
        }elseif($size == 200){
            $url = $dir.'200x200.jpg';
            $curl = $upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/'.'200x200.jpg';
        }elseif($size == 36){
            $url = $dir.'36x36.jpg';
            $curl = $upload.'avatar/'.$dir1.'/'.$dir2.'/'.$id.'/'.'36x36.jpg';
        }else{
            $url = Yii::app()->params['imgPath'].$upload.'avatar/'.$id.'/pictrue.jpg';
        }
        if(file_exists($curl)){
            return $url;
        }else{
            return Yii::app()->params['imgPath'].$upload.'public/avatar/12.jpg';
        }
    }
    /**
     * 显示时间
     */
    static public function showTime($t){
        $time = time() - $t;
        if($time < 60){
            $str = '刚刚发布';
        }else if($time < 60 * 60){
            $str = floor($time / 60).'分钟前发布';
        }else if($time < 60 * 60 * 24){
            if(date('Y-m-d')==date('Y-m-d',$t)){
                $str = '今天'.date('H:i',$t);
            }else{
                $str = '昨天'.date('H:i',$t);
            }
        }else if($time < 60 * 60 * 48){
            if(date('Y-m-d',strtotime("-1 day"))==date('Y-m-d',$t)){
                $str = '昨天'.date('H:i',$t);
            }else{
                $str = date('m月d日',$t);
            }
        }else if($time < 60 * 60 * 24* 365){
            $str = date('m月d日',$t);
        }else{
            $str = date('Y年m月d日',$t);
        }
        return $str;
    }

    /**
     * 字符截取
     *
     * @param $string
     * @param $length
     * @param $dot
     */
    public static function cutstr( $string, $length, $dot = '...', $charset = 'utf-8' ) {
        if ( strlen( $string ) <= $length )
            return $string;

        $pre = chr( 1 );
        $end = chr( 1 );
        $string = str_replace( array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), $string );

        $strcut = '';
        if ( strtolower( $charset ) == 'utf-8' ) {

            $n = $tn = $noc = 0;
            while ( $n < strlen( $string ) ) {

                $t = ord( $string[$n] );
                if ( $t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 ) ) {
                    $tn = 1;
                    $n ++;
                    $noc ++;
                } elseif ( 194 <= $t && $t <= 223 ) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif ( 224 <= $t && $t <= 239 ) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif ( 240 <= $t && $t <= 247 ) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif ( 248 <= $t && $t <= 251 ) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif ( $t == 252 || $t == 253 ) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n ++;
                }

                if ( $noc >= $length ) {
                    break;
                }

            }
            if ( $noc > $length ) {
                $n -= $tn;
            }

            $strcut = substr( $string, 0, $n );

        } else {
            for ( $i = 0; $i < $length; $i ++ ) {
                $strcut .= ord( $string[$i] ) > 127 ? $string[$i] . $string[++ $i] : $string[$i];
            }
        }

        $strcut = str_replace( array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), $strcut );

        $pos = strrpos( $strcut, chr( 1 ) );
        if ( $pos !== false ) {
            $strcut = substr( $strcut, 0, $pos );
        }
        return $strcut . $dot;
    }

    /**
     * 描述格式化
     * @param  $subject
     */
    public static function clearCutstr ($subject, $length = 0, $dot = '...', $charset = 'utf-8')
    {
        if ($length) {
            return XUtils::cutstr(strip_tags(str_replace(array ("\r\n" ), '', $subject)), $length, $dot, $charset);
        } else {
            return strip_tags(str_replace(array ("\r\n" ), '', $subject));
        }
    }

    public static function getIpLookup($ip = ''){
        if(empty($ip)){
            $ip = self::getClientIP();
        }
        $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
        if(empty($res)){ return false; }
        $jsonMatches = array();
        preg_match('#\{.+?\}#', $res, $jsonMatches);
        if(!isset($jsonMatches[0])){ return false; }
        $json = json_decode($jsonMatches[0], true);
        if(isset($json['ret']) && $json['ret'] == 1){
            $json['ip'] = $ip;
            unset($json['ret']);
        }else{
            return false;
        }
        return $json;
    }
    public static function pinyin($str){
        $xpinyin = new XPinYin();
        return $xpinyin->getAllPY($str);
    }
    public static function jibieArr(){
        return array(
            1=>'AAAAA级',
            2=>'AAAA级',
            3=>'AAA级',
            4=>'AA级',
            5=>'A级',
            6=>'非A级',
        );
    }
    public static function renqunArr(){
        return array(
            1=>'个人',
            2=>'同学',
            3=>'情侣',
            4=>'亲子',
            5=>'家庭',
            6=>'公司',
        );
    }
    public static function zhutiArr(){
        return array(
            1=>'爬山',
            2=>'赏花',
            3=>'踏青',
            4=>'采摘',
            5=>'沙漠',
            6=>'祈福',
            7=>'胡同',
            8=>'人文',
            9=>'寺庙',
            10=>'公园',
            11=>'美食',
            12=>'摄影',
            13=>'古镇',
            14=>'湿地',
            15=>'钓鱼',
            16=>'骑马',
            17=>'高尔夫',
            18=>'烧烤'

        );
    }
    public static function caizhaiArr(){
        return array(
            '蔬菜'=>array(
                1=>'雪菜',
                2=>'辣椒',
                3=>'蘑菇',
                4=>'彩椒',
                5=>'香椿',
                6=>'黄瓜',
                7=>'萝卜',
                8=>'圣女果',
                9=>'西红柿',
                10=>'茄子',
                11=>'秋葵',
                12=>'芹菜',
                13=>'丝瓜',
                14=>'香菇',
                15=>'竹笋',
                16=>'山药',
                17=>'芋艿',
                18=>'马兰头',
            ),
            '水果'=>array(
                19=>'李子',
                20=>'草莓',
                21=>'葡萄',
                22=>'桑葚',
                23=>'无花果',
                24=>'桃子',
                25=>'甜瓜',
                26=>'杏',
                27=>'西瓜',
                28=>'苹果',
                29=>'大枣',
                30=>'樱桃',
                31=>'梨',
                32=>'柿子',
                33=>'杨梅',
                34=>'枇杷',
                35=>'橘子',
                36=>'甘蔗',
                37=>'蓝莓',
                38=>'龙眼',
                39=>'荔枝',
                40=>'火龙果',
                41=>'杨桃',
                42=>'番石榴',
                43=>'猕猴桃',
            ),
            '干果'=>array(
                44=>'核桃',
                45=>'银杏',
                46=>'花生',
            ),
            '农作物'=>array(
                47=>'玉米',
                48=>'紫薯',
            ),
        );
    }
    //通过id 类型 获取名称
    public static function getType($id,$type){
        if($type=='jibie'){
            $arr = self::jibieArr();
            return $arr[$id];
        }
    }



    //添加图集数据
    public static function createArticleImage($id,$type,$path){
        $model = new ArticleImages();
        $model->article_id = $id;
        $model->type = $type;
        $model->image_path = $path;
        $model->is_show = 1;
        $model->is_delete = 0;
        $model->create_time = time();
        $model->save();
    }
    //添加周边数据
    public static function createArticleAmbitus($id,$v){
        $model = new ArticleAmbitus();
        $model->source_id = $id;
        $model->article_id = $v;
        $model->status = 1;
        $model->save();
    }
    //数字转换成月份
    public static function numToMonth($num){
        $month = '';
        switch($num){
            case 1:
                $month = '一月';
                break;
            case 2:
                $month = '二月';
                break;
            case 3:
                $month = '三月';
                break;
            case 4:
                $month = '四月';
                break;
            case 5:
                $month = '五月';
                break;
            case 6:
                $month = '六月';
                break;
            case 7:
                $month = '七月';
                break;
            case 8:
                $month = '八月';
                break;
            case 9:
                $month = '九月';
                break;
            case 10:
                $month = '十月';
                break;
            case 11:
                $month = '十一月';
                break;
            case 12:
                $month = '十二月';
                break;
        }
        return $month;
    }

    /**
     * 取得配置表信息
     * @param string $type  如果不填写 取得所有system信息  如果填写 取得单个信息
     * @return array
     */
    static public function getConfig($type=''){
        //email 配置
        $value = Yii::app()->cache->get('system_config');
        if($value === false){
            // 因为在缓存中没找到，重新生成 $value
            $info = Config::model()->findAll('type=:type',array(':type'=>'system'));
            $data = array();
            foreach($info as $v){
                $data[$v->name] = $v->value;
            }
            Yii::app()->cache->set('system_config',$data);
            $value = $data;
        }
        if($type){
            return $value[$type];
        }else{
            return $value;
        }
    }

    /**
     * @param $city_id
     * 通过cityid 获得city数据
     */
    static public function getCity($city_id){
        $info = CreateCity::model()->findByPk($city_id);
        return $info;
    }

    /**
     * 二维数组按照某一字段 进行排序
     * @param $arrUsers
     * @param $sort
     *     $sort = array(
    'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
    'field'     => 'age',       //排序字段
    );
     */

    static public function arrayListorder($arrUsers,$sort){
        $arrSort = array();
        foreach($arrUsers AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrUsers);
        }
        return $arrUsers;
    }

}



/**
 * XML编码
 * @param mixed $data 数据
 * @param string $root 根节点名
 * @param string $item 数字索引的子节点名
 * @param string $attr 根节点属性
 * @param string $id   数字索引子节点key转换的属性名
 * @param string $encoding 数据编码
 * @return string
 */
function xml_encode($data, $root='think', $item='item', $attr='', $id='id', $encoding='utf-8') {
    if(is_array($attr)){
        $_attr = array();
        foreach ($attr as $key => $value) {
            $_attr[] = "{$key}=\"{$value}\"";
        }
        $attr = implode(' ', $_attr);
    }
    $attr   = trim($attr);
    $attr   = empty($attr) ? '' : " {$attr}";
    $xml    = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
    $xml   .= "<{$root}{$attr}>";
    $xml   .= data_to_xml($data, $item, $id);
    $xml   .= "</{$root}>";
    return $xml;
}

/**
 * 数据XML编码
 * @param mixed  $data 数据
 * @param string $item 数字索引时的节点名称
 * @param string $id   数字索引key转换为的属性名
 * @return string
 */
function data_to_xml($data, $item='item', $id='id') {
    $xml = $attr = '';
    foreach ($data as $key => $val) {
        if(is_numeric($key)){
            $id && $attr = " {$id}=\"{$key}\"";
            $key  = $item;
        }
        $xml    .=  "<{$key}{$attr}>";
        $xml    .=  (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : $val;
        $xml    .=  "</{$key}>";
    }
    return $xml;
}


class XPinYin {
    private $pylist = array(
        'a'=>-20319,'ai'=>-20317,'an'=>-20304,'ang'=>-20295,'ao'=>-20292,
        'ba'=>-20283,'bai'=>-20265,'ban'=>-20257,'bang'=>-20242,'bao'=>-20230,'bei'=>-20051,'ben'=>-20036,'beng'=>-20032,'bi'=>-20026,'bian'=>-20002,'biao'=>-19990,'bie'=>-19986,'bin'=>-19982,'bing'=>-19976,'bo'=>-19805,'bu'=>-19784,
        'ca'=>-19775,'cai'=>-19774,'can'=>-19763,'cang'=>-19756,'cao'=>-19751,'ce'=>-19746,'ceng'=>-19741,'cha'=>-19739,'chai'=>-19728,'chan'=>-19725,'chang'=>-19715,'chao'=>-19540,'che'=>-19531,'chen'=>-19525,'cheng'=>-19515,'chi'=>-19500,'chong'=>-19484,'chou'=>-19479,'chu'=>-19467,'chuai'=>-19289,'chuan'=>-19288,'chuang'=>-19281,'chui'=>-19275,'chun'=>-19270,'chuo'=>-19263,'ci'=>-19261,'cong'=>-19249,'cou'=>-19243,'cu'=>-19242,'cuan'=>-19238,'cui'=>-19235,'cun'=>-19227,'cuo'=>-19224,
        'da'=>-19218,'dai'=>-19212,'dan'=>-19038,'dang'=>-19023,'dao'=>-19018,'de'=>-19006,'deng'=>-19003,'di'=>-18996,'dian'=>-18977,'diao'=>-18961,'die'=>-18952,'ding'=>-18783,'diu'=>-18774,'dong'=>-18773,'dou'=>-18763,'du'=>-18756,'duan'=>-18741,'dui'=>-18735,'dun'=>-18731,'duo'=>-18722,
        'e'=>-18710,'en'=>-18697,'er'=>-18696,
        'fa'=>-18526,'fan'=>-18518,'fang'=>-18501,'fei'=>-18490,'fen'=>-18478,'feng'=>-18463,'fo'=>-18448,'fou'=>-18447,'fu'=>-18446,
        'ga'=>-18239,'gai'=>-18237,'gan'=>-18231,'gang'=>-18220,'gao'=>-18211,'ge'=>-18201,'gei'=>-18184,'gen'=>-18183,'geng'=>-18181,'gong'=>-18012,'gou'=>-17997,'gu'=>-17988,'gua'=>-17970,'guai'=>-17964,'guan'=>-17961,'guang'=>-17950,'gui'=>-17947,
        'gun'=>-17931,'guo'=>-17928,
        'ha'=>-17922,'hai'=>-17759,'han'=>-17752,'hang'=>-17733,'hao'=>-17730,'he'=>-17721,'hei'=>-17703,'hen'=>-17701,'heng'=>-17697,'hong'=>-17692,'hou'=>-17683,'hu'=>-17676,'hua'=>-17496,'huai'=>-17487,'huan'=>-17482,'huang'=>-17468,'hui'=>-17454,
        'hun'=>-17433,'huo'=>-17427,
        'ji'=>-17417,'jia'=>-17202,'jian'=>-17185,'jiang'=>-16983,'jiao'=>-16970,'jie'=>-16942,'jin'=>-16915,'jing'=>-16733,'jiong'=>-16708,'jiu'=>-16706,'ju'=>-16689,'juan'=>-16664,'jue'=>-16657,'jun'=>-16647,
        'ka'=>-16474,'kai'=>-16470,'kan'=>-16465,'kang'=>-16459,'kao'=>-16452,'ke'=>-16448,'ken'=>-16433,'keng'=>-16429,'kong'=>-16427,'kou'=>-16423,'ku'=>-16419,'kua'=>-16412,'kuai'=>-16407,'kuan'=>-16403,'kuang'=>-16401,'kui'=>-16393,'kun'=>-16220,'kuo'=>-16216,
        'la'=>-16212,'lai'=>-16205,'lan'=>-16202,'lang'=>-16187,'lao'=>-16180,'le'=>-16171,'lei'=>-16169,'leng'=>-16158,'li'=>-16155,'lia'=>-15959,'lian'=>-15958,'liang'=>-15944,'liao'=>-15933,'lie'=>-15920,'lin'=>-15915,'ling'=>-15903,'liu'=>-15889,
        'long'=>-15878,'lou'=>-15707,'lu'=>-15701,'lv'=>-15681,'luan'=>-15667,'lue'=>-15661,'lun'=>-15659,'luo'=>-15652,
        'ma'=>-15640,'mai'=>-15631,'man'=>-15625,'mang'=>-15454,'mao'=>-15448,'me'=>-15436,'mei'=>-15435,'men'=>-15419,'meng'=>-15416,'mi'=>-15408,'mian'=>-15394,'miao'=>-15385,'mie'=>-15377,'min'=>-15375,'ming'=>-15369,'miu'=>-15363,'mo'=>-15362,'mou'=>-15183,'mu'=>-15180,
        'na'=>-15165,'nai'=>-15158,'nan'=>-15153,'nang'=>-15150,'nao'=>-15149,'ne'=>-15144,'nei'=>-15143,'nen'=>-15141,'neng'=>-15140,'ni'=>-15139,'nian'=>-15128,'niang'=>-15121,'niao'=>-15119,'nie'=>-15117,'nin'=>-15110,'ning'=>-15109,'niu'=>-14941,
        'nong'=>-14937,'nu'=>-14933,'nv'=>-14930,'nuan'=>-14929,'nue'=>-14928,'nuo'=>-14926,
        'o'=>-14922,'ou'=>-14921,
        'pa'=>-14914,'pai'=>-14908,'pan'=>-14902,'pang'=>-14894,'pao'=>-14889,'pei'=>-14882,'pen'=>-14873,'peng'=>-14871,'pi'=>-14857,'pian'=>-14678,'piao'=>-14674,'pie'=>-14670,'pin'=>-14668,'ping'=>-14663,'po'=>-14654,'pu'=>-14645,
        'qi'=>-14630,'qia'=>-14594,'qian'=>-14429,'qiang'=>-14407,'qiao'=>-14399,'qie'=>-14384,'qin'=>-14379,'qing'=>-14368,'qiong'=>-14355,'qiu'=>-14353,'qu'=>-14345,'quan'=>-14170,'que'=>-14159,'qun'=>-14151,
        'ran'=>-14149,'rang'=>-14145,'rao'=>-14140,'re'=>-14137,'ren'=>-14135,'reng'=>-14125,'ri'=>-14123,'rong'=>-14122,'rou'=>-14112,'ru'=>-14109,'ruan'=>-14099,'rui'=>-14097,'run'=>-14094,'ruo'=>-14092,
        'sa'=>-14090,'sai'=>-14087,'san'=>-14083,'sang'=>-13917,'sao'=>-13914,'se'=>-13910,'sen'=>-13907,'seng'=>-13906,'sha'=>-13905,'shai'=>-13896,'shan'=>-13894,'shang'=>-13878,'shao'=>-13870,'she'=>-13859,'shen'=>-13847,'sheng'=>-13831,'shi'=>-13658,'shou'=>-13611,'shu'=>-13601,'shua'=>-13406,'shuai'=>-13404,'shuan'=>-13400,'shuang'=>-13398,'shui'=>-13395,'shun'=>-13391,'shuo'=>-13387,'si'=>-13383,'song'=>-13367,'sou'=>-13359,'su'=>-13356,'suan'=>-13343,'sui'=>-13340,'sun'=>-13329,'suo'=>-13326,
        'ta'=>-13318,'tai'=>-13147,'tan'=>-13138,'tang'=>-13120,'tao'=>-13107,'te'=>-13096,'teng'=>-13095,'ti'=>-13091,'tian'=>-13076,'tiao'=>-13068,'tie'=>-13063,'ting'=>-13060,'tong'=>-12888,'tou'=>-12875,'tu'=>-12871,'tuan'=>-12860,'tui'=>-12858,'tun'=>-12852,'tuo'=>-12849,
        'wa'=>-12838,'wai'=>-12831,'wan'=>-12829,'wang'=>-12812,'wei'=>-12802,'wen'=>-12607,'weng'=>-12597,'wo'=>-12594,'wu'=>-12585,
        'xi'=>-12556,'xia'=>-12359,'xian'=>-12346,'xiang'=>-12320,'xiao'=>-12300,'xie'=>-12120,'xin'=>-12099,'xing'=>-12089,'xiong'=>-12074,'xiu'=>-12067,'xu'=>-12058,'xuan'=>-12039,'xue'=>-11867,'xun'=>-11861,
        'ya'=>-11847,'yan'=>-11831,'yang'=>-11798,'yao'=>-11781,'ye'=>-11604,'yi'=>-11589,'yin'=>-11536,'ying'=>-11358,'yo'=>-11340,'yong'=>-11339,'you'=>-11324,'yu'=>-11303,'yuan'=>-11097,'yue'=>-11077,'yun'=>-11067,
        'za'=>-11055,'zai'=>-11052,'zan'=>-11045,'zang'=>-11041,'zao'=>-11038,'ze'=>-11024,'zei'=>-11020,'zen'=>-11019,'zeng'=>-11018,'zha'=>-11014,'zhai'=>-10838,'zhan'=>-10832,'zhang'=>-10815,'zhao'=>-10800,'zhe'=>-10790,'zhen'=>-10780,'zheng'=>-10764,'zhi'=>-10587,'zhong'=>-10544,'zhou'=>-10533,'zhu'=>-10519,'zhua'=>-10331,'zhuai'=>-10329,'zhuan'=>-10328,'zhuang'=>-10322,'zhui'=>-10315,'zhun'=>-10309,'zhuo'=>-10307,'zi'=>-10296,'zong'=>-10281,'zou'=>-10274,'zu'=>-10270,'zuan'=>-10262,
        'zui'=>-10260,'zun'=>-10256,'zuo'=>-10254
    );


    /**
    +---------------------------------------------------------------------------------
     *    获取全部拼音
    +---------------------------------------------------------------------------------
     *    @return string
    +---------------------------------------------------------------------------------
     */
    public function getAllPY($chinese, $delimiter = '', $length = 0,$charset='utf-8') {
        if($charset != 'gb2312') $chinese = $this->_U2_Utf8_Gb($chinese);
        $py = $this->zh_to_pys($chinese, $delimiter);
        if($length) {
            $py = substr($py, 0, $length);
        }
        return $py;
    }

    /**
    +--------------------------------------------------------------------------------
     *    获取拼音首字母
    +--------------------------------------------------------------------------------
     *    @return string
    +--------------------------------------------------------------------------------
     */
    public function getFirstPY($chinese,$charset='utf-8'){
        if($charset != 'gb2312') $chinese = $this->_U2_Utf8_Gb($chinese);
        $result = '' ;
        for ($i=0; $i<strlen($chinese); $i++) {
            $p = ord(substr($chinese,$i,1));
            if ($p>160) {
                $q = ord(substr($chinese,++$i,1));
                $p = $p*256 + $q - 65536;
            }
            $result .= substr($this->zh_to_py($p),0,1);
        }
        return $result ;
    }

    public function _U2_Utf8_Gb($_C){
        $_String = '';
        if($_C < 0x80) $_String .= $_C;
        elseif($_C < 0x800)
        {
            $_String .= chr(0xC0 | $_C>>6);
            $_String .= chr(0x80 | $_C & 0x3F);
        }elseif($_C < 0x10000){
            $_String .= chr(0xE0 | $_C>>12);
            $_String .= chr(0x80 | $_C>>6 & 0x3F);
            $_String .= chr(0x80 | $_C & 0x3F);
        } elseif($_C < 0x200000) {
            $_String .= chr(0xF0 | $_C>>18);
            $_String .= chr(0x80 | $_C>>12 & 0x3F);
            $_String .= chr(0x80 | $_C>>6 & 0x3F);
            $_String .= chr(0x80 | $_C & 0x3F);
        }
        return iconv('UTF-8', 'GB2312', $_String);
    }

    private function zh_to_py($num, $blank = '') {
        if($num>0 && $num<160 ) {
            return chr($num);
        } elseif ($num<-20319||$num>-10247) {
            return $blank;
        } else {
            foreach ($this->pylist as $py => $code) {
                if($code > $num) break;
                $result = $py;
            }
            return $result;
        }
    }

    private function zh_to_pys($chinese, $delimiter = ' ', $first=0){
        $result = array();
        for($i=0; $i<strlen($chinese); $i++) {
            $p = ord(substr($chinese,$i,1));
            if($p>160) {
                $q = ord(substr($chinese,++$i,1));
                $p = $p*256 + $q - 65536;
            }
            $result[] = $this->zh_to_py($p);
            if ($first) {
                return $result[0];
            }
        }
        return implode($delimiter, $result);
    }
}